package com.ihr360.excel.aggregatemodule.controller;

import com.alibaba.fastjson.JSONObject;
import com.ihr360.commons.context.session.Ihr360SessionContextHolder;
import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.vo.ResultInfo;
import com.ihr360.excel.aggregatemodule.service.ExcelAggregateService;
import com.ihr360.excel.vo.ImportResult;
import com.ihr360.excel.vo.ProgressContext;
import com.ihr360.excel.vo.ProgressContextFile;
import com.ihr360.excel.vo.ProgressResult;
import com.ihr360.shared.advice.response.DisableResponseAdvice;
import com.ihr360.sharedservice.api.DataCacheService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author richey
 */
@RestController
@RequestMapping("/excel")
@DisableResponseAdvice
public class ExcelAggregateController {

    Logger logger = LoggerFactory.getLogger(ExcelAggregateController.class);

    @Autowired
    private DataCacheService dataCacheService;

    @Autowired
    private ExcelAggregateService excelAggregateService;


    /**
     * @param businessUniqueKey 业务唯一标识，如果一个业务模块可能存在多次异步导入，则用业务唯一标识辅助确定唯一进度
     * @param moduleCode
     * @param file
     * @param userInfo
     * @throws IOException
     */
    @PostMapping(value = "/upload")
    public void upload(@RequestParam(required = false) String businessUniqueKey,
                       @RequestParam String moduleCode,
                       @RequestParam(required = false) String extraParams,
                       MultipartFile file,
                       AuthUserInfo userInfo) throws IOException {

        String userId = userInfo.getUserId();
        String companyId = userInfo.getCompanyId();
        ProgressContextFile contextFile = new ProgressContextFile(IOUtils.toByteArray(file.getInputStream()), file.getOriginalFilename());
        ProgressContext progressContext = new ProgressContext(companyId, userId, moduleCode, businessUniqueKey, contextFile);

        if (StringUtils.isNotEmpty(extraParams)) {
            progressContext.setExtraParams((Map<String, Object>) JSONObject.parse(extraParams));
        }


        String progress = dataCacheService.get(progressContext.getProgressKey());
        if (StringUtils.isNotEmpty(progress)) {
            excelAggregateService.interruptProgress(progressContext);
//            throw new Ihr360Exception(null, "导入失败，存在未结束流程！");
        }

        //生成进度标识
        String progressKey = progressContext.getProgressKey();
        dataCacheService.put(progressKey, "10");
        logger.info("开始处理上传文件,processKey{}", progressKey);

        excelAggregateService.preHandle(progressContext);
    }

    // 获取进度信息和结果
    @PostMapping("/progress")
    public ProgressResult getProgressResult(@RequestParam String moduleCode,
                                            @RequestParam(required = false) String businessUniqueKey,
                                            AuthUserInfo userInfo) {
        ProgressContext progressContext = new ProgressContext(userInfo.getCompanyId(), userInfo.getUserId(), moduleCode, businessUniqueKey, null);
        return excelAggregateService.getProgressResult(progressContext);
    }

    /**
     * 获取所有正确的数据
     *
     * @param moduleCode
     * @param businessUniqueKey
     * @param userInfo
     * @return
     */
    @PostMapping("/importResult")
    public ImportResult getCorrectDatas(@RequestParam String moduleCode,
                                        @RequestParam(required = false) String businessUniqueKey,
                                        AuthUserInfo userInfo) {
        ProgressContext progressContext = new ProgressContext(userInfo.getCompanyId(), userInfo.getUserId(), moduleCode, businessUniqueKey, null);
        return excelAggregateService.getImportResult(progressContext);
    }


    /**
     * 中断流程
     *
     * @return
     */
    @PostMapping("/interruptProgress")
    public ResultInfo interruptProgress(@RequestParam String moduleCode,
                                        @RequestParam(required = false) String businessUniqueKey,
                                        AuthUserInfo userInfo) {

        ProgressContext progressContext = new ProgressContext(userInfo.getCompanyId(), userInfo.getUserId(), moduleCode, businessUniqueKey, null);
        return excelAggregateService.interruptProgress(progressContext);
    }


    /**
     * 下载错误文件
     *
     * @return
     */
    @GetMapping(value = "/errorFile", produces = ("text/html;charset=UTF-8"))
    public void interruptProgress(@RequestParam String moduleCode,
                                  @RequestParam(required = false) String businessUniqueKey,
                                  @RequestParam(required = false) Boolean onlyError,
                                  HttpServletResponse response) throws IOException {

        AuthUserInfo userInfo = Ihr360SessionContextHolder.getSessionContext().getSession().getUserInfo();
        ProgressContext progressContext = new ProgressContext(userInfo.getCompanyId(), userInfo.getUserId(), moduleCode, businessUniqueKey, null);
        if (onlyError != null && onlyError.booleanValue()) {
            progressContext.setOnlyErrorDownload(onlyError);
        }

        response.setContentType("application/vnd.ms-excel");
        String fileName = new String(("errorFile.xls").getBytes("UTF-8"), "iso-8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        excelAggregateService.downloadErrorFile(progressContext, response.getOutputStream());
    }


}
